﻿using CoreModule;
using HandyControl.Properties.Langs;
using Microsoft.Extensions.Logging;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using ResourceLocalization;
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using UIModule;
using UIModule.Views;
using WPFLocalizeExtension.Engine;
using Yuwell.BloodGlucose.BluetoothDataParser.App.Views;
namespace Yuwell.BloodGlucose.BluetoothDataParser.App.ViewModels
{
    /// <summary>
    /// 主 程序 
    /// </summary>
    public class MainWindowViewModel : BindableBase, IWindowLifetime
    {
        /// <summary>
        /// 历史界面 
        /// </summary>
        public ICommand GoHistoryCommand => new Prism.Commands.DelegateCommand(GoHistory);

        /// <summary>
        /// 分析界面
        /// </summary>
        public ICommand GoAnalysisCommand => new Prism.Commands.DelegateCommand(GoAnalysis);

        /// <summary>
        /// 显示蓝牙界面
        /// </summary>
        public ICommand ShowBluetoothDataPickerCommand => new Prism.Commands.DelegateCommand(ShowBluetoothDataPicker);
        /// <summary>
        /// 日志
        /// </summary>
        ILogger Logger { get; set; }


        /// <summary>
        /// 中文
        /// </summary>
        public SolidColorBrush ChineseForeground { get; set; } = new SolidColorBrush(Colors.Black);

        /// <summary>
        /// 英文
        /// </summary>
        public SolidColorBrush EnglishForeground { get; set; } = new SolidColorBrush(Colors.Black);


        public ICommand SelectChinese => new Prism.Commands.DelegateCommand(()=> { SelectLanguage(ResLanguage.Zh); });

        /// <summary>
        /// 
        /// </summary>
        public ICommand SelectEnglish=> new Prism.Commands.DelegateCommand(() => { SelectLanguage(ResLanguage.En); });

        /// <summary>
        /// 
        /// </summary>
        public ICommand SelectPortugal => new Prism.Commands.DelegateCommand(() => { SelectLanguage(ResLanguage.pt); });
        

        /// <summary>
        /// 显示 配置 界面
        /// </summary>
        public ICommand SettingCommand => new Prism.Commands.DelegateCommand<FrameworkElement>(Setting);
        /// <summary>
        /// 显示 帮助 文档
        /// </summary>
        public ICommand ShowDocumentCommand => new Prism.Commands.DelegateCommand<FrameworkElement>(ShowDocument);

        /// <summary>
        /// 关于 我们
        /// </summary>
        public ICommand AboutCommand => new Prism.Commands.DelegateCommand(About);

        /// <summary>
        /// 关闭 确认 
        /// </summary>
        public ICommand CloseWindowCommand => new Prism.Commands.DelegateCommand<FrameworkElement>(CloseWindow);

        /// <summary>
        /// 
        /// </summary>
        public string CurrentLanguageName { get; set; } = "中文";

        /// <summary>
        /// 关闭 确认
        /// </summary>
        /// <param name="mask"></param>
        public void CloseWindow(FrameworkElement mask)
        {

            mask.Visibility = Visibility.Visible;

            var window = mask.GetWindow();

            if (ContainerProvider.IsRegistered<Window>(CoreConstant.CloseWindowView))
            {
                var closeWindow = ContainerProvider.Resolve<Window>(CoreConstant.CloseWindowView);

                if (window != null)
                {
                    closeWindow.Owner = window;
                }

                if (closeWindow.ShowDialog() == true)
                {
                    this.WindowClosing?.Invoke(this, EventArgs.Empty);
                    Application.Current.Shutdown();
                    return;
                }
                mask.Visibility = Visibility.Hidden;
            }
            else
            {
                CloseWindow closeWindow = new CloseWindow();

                if (window != null)
                {
                    closeWindow.Owner = window;
                }

                if (closeWindow.ShowDialog() == true)
                {
                    this.WindowClosing?.Invoke(this, EventArgs.Empty);
                    Application.Current.Shutdown();
                    return;
                }
                mask.Visibility = Visibility.Hidden;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public void GoHistory()
        {
            if (this.RegionViewKind == RegionViewKind.History)
            {
                return;
            }
            this.HighlightHistroyMenu();
            var navigationParameters = new NavigationParameters
                {
                    {
                          CoreConstant.BluetoothDataPickerResultKey, Cache.BluetoothDataPickerResult
                    }
                };


            this.RegionManager.RequestNavigate(CoreModule.CoreConstant.MainRegion, CoreModule.CoreConstant.HistoryView,navigationParameters);
            
        }
        /// <summary>
        /// 
        /// </summary>
        public void GoAnalysis()
        {
            if (this.RegionViewKind== RegionViewKind.Analysis)
            {
                return;
            }

            this.HighlightAnalysisMenu();
            var navigationParameters = new NavigationParameters
                {
                    {
                          CoreConstant.BluetoothDataPickerResultKey, Cache.BluetoothDataPickerResult
                    }
                };

            this.RegionManager.RequestNavigate(CoreModule.CoreConstant.MainRegion, CoreModule.CoreConstant.AnalysisView, navigationParameters);
        }
        /// <summary>
        /// 
        /// </summary>
        public void ShowBluetoothDataPicker()
        {

            var kk = this.ContainerProvider.Resolve<BluetoothDataPicker>(CoreConstant.BluetoothDataPickerWindow);
            kk.ShowDialog();
           
        }
         
        /// <summary>
        /// 
        /// </summary>
        public void About()
        {
            if (this.RegionViewKind == RegionViewKind.MeasurementResult)
            {
                ContainerProvider.Resolve<INotifier>().ShowWarning("当前在测量过程中，请先保存测量结果");
                return;
            }
            RegionManager.RequestNavigate(CoreConstant.MainRegion, UIConstant.AboutView);
        }

        /// <summary>
        /// 
        /// </summary>
        public SolidColorBrush GoHistroyCommandBackground { get; set; } = new SolidColorBrush(Colors.White);
        public SolidColorBrush GoAnalysisCommandBackground { get; set; } = new SolidColorBrush(Colors.Transparent);
        

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mask"></param>
        public void ShowDocument(FrameworkElement mask)
        {
            try
            {
                var fileName = "多参数程序使用说明书.pdf";
                var filePath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName);
                if (System.IO.File.Exists(filePath))
                {
                    System.Diagnostics.Process.Start("explorer.exe", filePath);
                }
            }
            catch (Exception ex)
            {

            }
        }

        public void UpdateCurrentLanguageName(ResLanguage resLanguage)
        {
            switch (resLanguage)
            {
                case ResLanguage.None:
                    this.CurrentLanguageName = "中文";
                    break;
                case ResLanguage.Zh:
                    this.CurrentLanguageName = "中文";
                    break;
                case ResLanguage.pt:
                    this.CurrentLanguageName = "Português";
                    break;
                case ResLanguage.En:
                    this.CurrentLanguageName = "English";
                    break;
                default:
                    break;
            }


            this.RaisePropertyChanged(nameof(this.CurrentLanguageName));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="resLanguage"></param>
        public void SelectLanguage(ResLanguage resLanguage)
        {
           
            UseResource(resLanguage);
            UpdateCurrentLanguageName(resLanguage);
             
          
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mask"></param>
        public void Setting(FrameworkElement mask)
        {
 
        }

        /// <summary>
        /// 
        /// </summary>
        IContainerProvider ContainerProvider { get; set; }


      IRegionManager RegionManager { get; set; }

        public MainWindowViewModel(IRegionManager regionManager,
                                IContainerProvider containerProvider,
                                ILogger logger)
        {

            RegionManager = regionManager;
            ContainerProvider = containerProvider;
          
            Logger = logger;

            Logger.LogInformation("系统启动");


        

            UpdateCurrentLanguageName(ResLanguageConfiguration.Load().SettingResLanguage);


        }
     
        /// <summary>
        /// 
        /// </summary>

        public void HighlightHistroyMenu()
        {
            GoHistroyCommandBackground = new SolidColorBrush(Colors.White);
            GoAnalysisCommandBackground = new SolidColorBrush(Colors.Transparent);
            this.RaisePropertyChanged(nameof(GoHistroyCommandBackground));
            this.RaisePropertyChanged(nameof(GoAnalysisCommandBackground));

        }

        /// <summary>
        /// 
        /// </summary>
        public void HighlightAnalysisMenu()
        {
           

            GoHistroyCommandBackground = new SolidColorBrush(Colors.Transparent);
            GoAnalysisCommandBackground = new SolidColorBrush(Colors.White);
            this.RaisePropertyChanged(nameof(GoHistroyCommandBackground));
            this.RaisePropertyChanged(nameof(GoAnalysisCommandBackground));
        }

        /// <summary>
        /// 
        /// </summary>
        public void ShowMask()
        {
            var frameworkElement = ContainerProvider.Resolve<FrameworkElement>(CoreConstant.MaskKey);
            frameworkElement.Visibility = Visibility.Visible;
        }
        //

        public void CloseMask()
        {
            var frameworkElement = ContainerProvider.Resolve<FrameworkElement>(CoreConstant.MaskKey);
            frameworkElement.Visibility = Visibility.Collapsed;
        }

        public WindowMode _windowMode = WindowMode.UI;

        public WindowMode WindowMode
        {
            get { return _windowMode; }
            set
            {
                _windowMode = value;
                RaisePropertyChanged(nameof(this.WindowMode));
            }
        }
         
        /// <summary>
        /// 
        /// </summary>
        RegionViewKind _regionViewKind = RegionViewKind.None;
        /// <summary>
        /// 
        /// </summary>
        public RegionViewKind RegionViewKind
        {
            get
            {
                return _regionViewKind;
            }
            set
            {

                if (value != _regionViewKind)
                {
                    _regionViewKind = value;
                    this.RegionViewKindChanged?.Invoke(this, EventArgs.Empty);
                }
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="resLanguage"></param>
        private void ChangeResourceProvider(ResourceLocalization.ResLanguage resLanguage)
        {
            
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="regionViewKind"></param>
        /// <returns></returns>
        private string GetRegionViewKindNavigateUrl(RegionViewKind regionViewKind)
        {
            switch (regionViewKind)
            {
                case RegionViewKind.None:
                    return CoreConstant.HistoryView;
                case RegionViewKind.Analysis:
                    return CoreConstant.AnalysisView;
                case RegionViewKind.History:
                    return CoreConstant.HistoryView;
             
            }
            return CoreConstant.HistoryView;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="resLanguage"></param>
        private void MainRegionRequestNavigate(ResourceLocalization.ResLanguage resLanguage)
        {

            var windowLifetime = ContainerProvider.Resolve<IWindowLifetime>();

            var regionManager = ContainerProvider.Resolve<IRegionManager>();

            var regionViewKind = windowLifetime.RegionViewKind;

            var url = GetRegionViewKindNavigateUrl(regionViewKind);
            var navigationParameters = new NavigationParameters
                {
                    {
                          CoreConstant.BluetoothDataPickerResultKey, Cache.BluetoothDataPickerResult
                    }
                };
            ///中心
            if (url == CoreConstant.AnalysisView)
            {
                regionManager.RequestNavigate(CoreConstant.MainRegion,CoreConstant.BlankView);
                regionManager.RequestNavigate(CoreConstant.MainRegion, CoreConstant.AnalysisView, navigationParameters);
            }
            else
            {
                regionManager.RequestNavigate(CoreConstant.MainRegion, CoreConstant.HistoryView, navigationParameters);
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="resLanguage"></param>
        private void UseResourceLocalization(ResourceLocalization.ResLanguage resLanguage)
        {
            LocalizeDictionary.Instance.SetCurrentThreadCulture = true;
            LocalizeDictionary.Instance.Culture = new CultureInfo(resLanguage.GetDescription());
            ChangeResourceProvider(resLanguage);
            MainRegionRequestNavigate(resLanguage);

        }
         
        /// <summary>
        /// 
        /// </summary>
        /// <param name="resLanguage"></param>

        public void UseResource(ResLanguage resLanguage)
        {
            UseResourceLocalization(resLanguage);

            App.UsingResLanguage = resLanguage;
            var resLanguageConfiguration = ResourceLocalization.ResLanguageConfiguration.Load();
            resLanguageConfiguration.SettingResLanguage = resLanguage;
            resLanguageConfiguration.Save();

        }
      

        /// <summary>
        /// 
        /// </summary>
        public event EventHandler<EventArgs> WindowClosing;
        public event EventHandler<WindowModeEventArgs> WindowModeChanged;
        public event EventHandler<EventArgs> RegionViewKindChanged;
    }
}
